package Server.netty.nettyInitializer;

import Server.netty.handler.NettyRPCServerHandler;
import Server.provider.ServiceProvider;
import common.serializer.myCode.MyDecoder;
import common.serializer.myCode.MyEncoder;
import common.serializer.mySerializer.JsonSerializer;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.serialization.ClassResolver;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;
import lombok.AllArgsConstructor;

@AllArgsConstructor
public class NettyServerInitializer extends ChannelInitializer<SocketChannel> {

    private ServiceProvider serviceProvider;

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        // 责任链模式：每个Socket有一个pipeline，用于定义数据处理流程，pipeline传入handler，按照顺序处理
        ChannelPipeline pipeline = ch.pipeline();
//        // 消息格式【长度】【消息体】，解决沾包问题
//        pipeline.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
//        // 计算当前待发送消息的长度，写入前4个字节中
//        pipeline.addLast(new LengthFieldPrepender(4));
//        // 消息编码器:Java序列化方式，netty自带解码编码支持传输该结构
//        pipeline.addLast(new ObjectEncoder());
//        // 消息解码器：Netty的OjbectDecoder，用于将字节解码为Java对象,解码器构造函数传入ClassResolver对象，解析类名并加载对应的类
//        pipeline.addLast(new ObjectDecoder(new ClassResolver() {
//            @Override
//            public Class<?> resolve(String className) throws ClassNotFoundException {
//                return Class.forName(className);
//            }
//        }));

        // 使用自定义编/解码器(先添加解码器，再添加编码器)
        pipeline.addLast(new MyDecoder());
        pipeline.addLast(new MyEncoder(new JsonSerializer()));
        // 将NettyRPCServerHandler加入到pipeline中，用于处理请求
        pipeline.addLast(new NettyRPCServerHandler(serviceProvider));
    }
}
